<?php

namespace app\common\utils;

class CommonSign
{
    // 通用签名工具类

    // 随机字符串
    public static function nonce($digit = 16, $nonce = '', $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
    {
        for ($i = 0; $i < $digit; $i++) {
            $nonce .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $nonce;
    }

    /**
     * 第三方 通用签名
     * @param array $params  请求参数
     * @return string  签名
     */
    public static function commonSign(&$params, $appId, $timestamp, $nonce)
    {
        $params['appKey'] = self::getAppKeyByAppid($appId);
        $params['timestamp'] = $timestamp;
        $params['nonce'] = $nonce;
        $params['appId'] = $appId;

        ksort($params);

        $queryParams = [];
        foreach ($params as $key => $value) {
            $queryParams[] = $key . '=' . trim($value);
        }
        $sign = sha1(implode('&', $queryParams));
        unset($params['appKey']);
        return $sign;
    }

    /**
     * 第三方 通用签名
     * @param array $params  请求参数
     * @return string  签名
     */
    // public static function commonSign2(&$params, $appId, $timestamp, $nonce)
    // {
    //     $params['appKey'] = self::getAppKeyByAppid($appId);
    //     $params['timestamp'] = $timestamp;
    //     $params['nonce'] = $nonce;
    //     $params['appId'] = $appId;

    //     ksort($params);

    //     $queryParams = [];
    //     foreach ($params as $key => $value) {
    //         $queryParams[] = $key . '=' . trim($value);
    //     }
    //     return implode('&', $queryParams);
    // }

    public static function checkAppid($appId)
    {
        $appidList = config('open_sign.appid_list');
        return array_key_exists($appId, $appidList);
    }


    public static function getAppKeyByAppid($appId)
    {
        $appidList = config('open_sign.appid_list');
        return array_key_exists($appId, $appidList) ? $appidList[$appId] : '';
    }
}
